extends Node2D

# 防御塔类型（在编辑器中设置）
@export var tower_type: String = "胡小刀"

# 基础属性
var base_attack: int = 0     # 基础攻击力
var temp_attack: int = 0     # 临时攻击加成
var base_health: int = 0     # 基础生命值
var health: int = 0          # 当前生命值

# 战斗属性
@export var attack_range: float = 150    # 攻击范围
@export var attack_cooldown: float = 1.0 # 攻击冷却
var attack_timer: float = 0.0            # 攻击计时器
var target = null            # 当前目标怪物

func _ready():
	# 初始化防御塔属性
	match tower_type:
		"紫玲珑":
			base_attack = 5
			base_health = 30
		"胡小刀":
			base_attack = 8
			base_health = 20
		"万仞海":
			base_attack = 3
			base_health = 40
	
	health = base_health
	temp_attack = 0
	
	# 更新UI
	update_label()
	
	# 加入防御塔分组
	add_to_group("towers")  
	
	print("防御塔 ", tower_type, " 已就绪！位置: ", global_position)

# 获取总攻击力
func get_total_attack():
	return base_attack + temp_attack

# 更新塔顶标签
func update_label():
	if has_node("Label"):
		$Label.text = "%s\n攻: %d(%d)\n命: %d" % [tower_type, get_total_attack(), temp_attack, health]

# 增加临时攻击力
func add_temp_attack(amount: int):
	temp_attack += amount
	update_label()
	print("防御塔 ", tower_type, " 获得临时攻击力 +", amount)

# 增加生命值
func add_health(amount: int):
	health += amount
	update_label()
	print("防御塔 ", tower_type, " 获得生命值 +", amount)

# 受到伤害
func take_damage(damage: int):
	health -= damage
	update_label()
	
	# 生命值归零时销毁防御塔
	if health <= 0:
		print("防御塔 ", tower_type, " 被摧毁！")
		queue_free()

# 每帧更新
func _process(delta):
	# 目标无效时清除引用
	if target and not is_instance_valid(target):
		target = null
	
	# 没有目标时尝试寻找
	if !target:
		find_target()
		return
	
	# 检查目标是否仍在范围内
	if global_position.distance_to(target.global_position) > attack_range:
		target = null
		return
	
	# 更新攻击计时器
	attack_timer += delta
	
	# 攻击冷却结束且目标有效
	if attack_timer >= attack_cooldown and is_instance_valid(target):
		attack_timer = 0
		attack_target()

# 寻找目标
func find_target():
	var monsters = get_tree().get_nodes_in_group("monsters")
	var closest = null
	var min_distance = INF
	
	for monster in monsters:
		if is_instance_valid(monster):
			var distance = global_position.distance_to(monster.global_position)
			if distance < min_distance and distance <= attack_range:
				min_distance = distance
				closest = monster
	
	if closest:
		target = closest

# 攻击目标
func attack_target():
	if is_instance_valid(target):
		# 造成伤害
		target.take_damage(get_total_attack())
		
		# 触发攻击事件
		get_parent().attack_event.emit(self)
		
		# 紫玲珑特殊效果：攻击时触发攻击力增益
		if tower_type == "紫玲珑":
			get_parent().attack_buff_event.emit(1, self)

# ===== 技能处理 =====

# 处理攻击事件（万人海响应）
func handle_attack_event(source):
	# 只有万人海响应攻击事件
	if tower_type == "万仞海":
		print("万人海响应攻击事件")
		
		# 随机选择一个友方防御塔
		var towers = get_tree().get_nodes_in_group("towers")
		if towers.size() > 0:
			var random_tower = towers[randi() % towers.size()]
			
			# 增强随机防御塔
			random_tower.add_temp_attack(2)
			random_tower.add_health(1)
			
			print("万人海增强了 ", random_tower.tower_type)

# 处理攻击力增益事件（虎啸刀和紫玲珑响应）
func handle_attack_buff_event(amount, source):
	# 虎啸刀：获得等量攻击力
	if tower_type == "胡小刀":
		print("虎啸刀响应攻击力增益")
		add_temp_attack(amount)
	
	# 紫玲珑：自身体力+1
	if tower_type == "紫玲珑":
		print("紫玲珑响应攻击力增益")
		add_health(1)
